<!--用户分析-->
<template>
  <div class="user">
    <div class="title">App用户分析</div>
    <div class="header">
      <div class="today-register">
        <div class="left">
          <div class="head">今日注册用户</div>
          <div class="num">{{ devicesData.tregistrants }}</div>
        </div>
        <div class="right">昨日：{{ devicesData.yregistrants }}</div>
      </div>
      <div class="accumulate-register">
        <div class="left">
          <div class="head">累计注册用户</div>
          <div class="num">{{ devicesData.totalRegistrants }}</div>
        </div>
        <div class="right"></div>
      </div>
      <div class="today-active">
        <div class="left">
          <div class="head">今日活跃用户</div>
          <div class="num">{{ devicesData.tactiveUser }}</div>
        </div>
        <div class="right">昨日：{{ devicesData.yactiveUser }}</div>
      </div>
    </div>
    <div class="search">
      <div class="name">用户趋势</div>
      <div class="search-right">
        <div class="tab">
          <div class="day" :class="{'active': dateType === 'day'}" @click="handleDate('day')">按日查询</div>
          <div class="mounth" :class="{'active': dateType === 'mounth'}" @click="handleDate('mounth')">按月查询</div>
        </div>
        <el-date-picker
          v-show="dateType === 'day'"
          ref="datePicker"
          v-model="dayValue"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="date-picker"
          :picker-options="pickerOptions"
          clearable
          @blur="isRestart = true"
          @change="handleFormat">
        </el-date-picker>
        <el-date-picker
          v-show="dateType === 'mounth'"
          ref="monthPicker"
          v-model="mounthValue"
          type="monthrange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="date-picker"
          :picker-options="pickerMounthOptions"
          clearable
          @blur="isRestart = true"
          @change="handleFormat">
        </el-date-picker>
      </div>
    </div>
    <div class="register-box">
      <div class="header">
        <div class="">注册用户数</div>
        <el-button type="primary" class="button-container" size="14" @click="handleExports('registers')">导出</el-button>
      </div>
      <div id="main" ref="registerEcharts" style="height: 420px"></div>
    </div>
    <div class="active-box">
      <div class="header">
        <div class="">活跃用户数</div>
        <el-button type="primary" class="button-container" size="14" @click="handleExports('activeUser')">导出</el-button>
      </div>
      <div ref="activeEcharts" style="height: 420px"></div>
    </div>
  </div>
</template>
<script>
import moment from 'moment'
import echarts from 'echarts'
import 'echarts/lib/chart/line'
import 'echarts/lib/component/title'
import { statisticalUser, statisticalExport } from '@/api/device-data/device'
export default {
  name: 'userAnalysis',
  data() {
    return {
      dayValue: [moment().subtract(7, 'days').format('YYYY-MM-DD'), moment().subtract(1, 'days').format('YYYY-MM-DD')],
      mounthValue: [moment(moment().format("YYYY-MM-DD")).subtract(5, 'months').startOf('month').format('YYYY-MM-DD'), moment().format("YYYY-MM-DD")],
      dateType: 'day', // 日期类型 day选择天 mounth选择月
      startDay: moment().subtract(7, 'days').format('YYYY-MM-DD'), // 开始时间 天
      endDay: moment().subtract(1, 'days').format('YYYY-MM-DD'), // 结束时间 天
      startMounth: '', // 开始时间 月
      endMounth: '', // 结束时间 月
      isComponentAlive: true,
      registerChartX: [],
      registerChartY: [],
      activeEchartsX: [],
      activeEchartsY: [],
      devicesData: {} // 设备数据
    }
  },
  computed: {
    pickerOptions() {
      const self = this // 保存组件实例的引用
      return {
        onPick: ({ maxDate, minDate }) => {
          self.isRestart = false
          self.pickerMinDate = minDate ? minDate.getTime() : ''
          if (maxDate) {
            self.pickerMinDate = ''
          }
        },
        disabledDate: (time) => {
          const today = new Date()
          if (self.pickerMinDate !== '') {
            const oneYearInMilliseconds = 61 * 24 * 3600 * 1000 // 天数62
            const minTime = self.pickerMinDate - oneYearInMilliseconds
            const maxTime = self.pickerMinDate + oneYearInMilliseconds
            // 禁用超过允许的日期范围和未来的日期
            return time.getTime() < minTime || time.getTime() > maxTime || time.getTime() > today.getTime()
          }
          return time.getTime() > today.getTime() // 禁用未来的日期
        }
      }
    },
    pickerMounthOptions() {
      return {
        onPick: ({ maxDate, minDate }) => {
          self.isRestart = false
          self.pickerMinDate = minDate ? minDate.getTime() : ''
          if (maxDate) {
            self.pickerMinDate = ''
          }
        },
        disabledDate: (time) => {
          const today = new Date()
          const currentMonthLastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0) // 当月的最后一天
          // 禁用所有超过当月的未来日期
          if (time.getTime() > currentMonthLastDay.getTime()) {
            return true
          }
          if (self.pickerMinDate !== '') {
            const oneYearLater = new Date(new Date(self.pickerMinDate).setMonth(new Date(self.pickerMinDate).getMonth() + 11))
            const oneYearFront = new Date(new Date(self.pickerMinDate).setMonth(new Date(self.pickerMinDate).getMonth() - 11))
            return time.getTime() > currentMonthLastDay.getTime() || time.getTime() < oneYearFront || time.getTime() > oneYearLater
          }
          return false
        }
      }
    }
  },
  mounted() {
    this.init()
  },
  beforeDestroy() {
    this.isComponentAlive = false
    // 在组件销毁之前清理 ECharts 实例
    if (this.registerChart) {
      // 使用 echarts 的 dispose 方法清理图表实例
      this.registerChart.dispose()
      this.registerChart = null
    }
    if (this.activeEcharts) {
      // 使用 echarts 的 dispose 方法清理图表实例
      this.activeEcharts.dispose()
      this.activeEcharts = null
    }
  },
  methods: {
    init() {
      const params = {
        type: this.dateType,
        startDate: this.dateType === 'day' ? this.startDay : this.startMounth,
        endDate: this.dateType === 'day' ? this.endDay : this.endMounth
      }
      statisticalUser(params).then(res => {
        this.devicesData = res.data.data
        this.registerChartX = []
        this.registerChartY = []
        this.activeEchartsX = []
        this.activeEchartsY = []
        res.data.data.registrantsList.forEach(item => {
          this.registerChartX.push(item.date)
          this.registerChartY.push(item.value)
        })
        res.data.data.activeUserList.forEach(item => {
          this.activeEchartsX.push(item.date)
          this.activeEchartsY.push(item.value)
        })

        if (this.isComponentAlive) {
          // 创建 ECharts 实例
          const registerChart = echarts.init(this.$refs.registerEcharts)
          const activeEcharts = echarts.init(this.$refs.activeEcharts)
          window.addEventListener('resize', () => {
            registerChart.resize()
            activeEcharts.resize()
          })
          registerChart.showLoading()
          // 调用 setOption 方法配置图表
          registerChart.setOption({
            xAxis: {
              axisLabel: {
                textStyle: {
                  color: 'rgba(1, 1, 1, 0.4)' // 设置 x 轴字体颜色
                }
              },
              axisLine: {
                lineStyle: {
                  color: 'rgba(1, 1, 1, 0.1)' // 设置 x 轴线颜色
                }
              },
              axisTick: {
                show: false // 设置是否显示 X 轴的刻度线
              },
              data: this.registerChartX
            },
            yAxis: {
              axisLabel: {
                textStyle: {
                  color: 'rgba(1, 1, 1, 0.4)' // 设置 y 轴字体颜色
                }
              },
              axisLine: {
                lineStyle: {
                  color: 'rgba(1, 1, 1, 0.1)' // 设置 x 轴线颜色
                }
              },
              axisTick: {
                show: false // 设置是否显示 X 轴的刻度线
              },
              splitLine: {
                // show: false // 设置是否显示 Y 轴的分隔线
                lineStyle: {
                  color: 'rgba(1, 1, 1, 0.1)'
                }
              }
            },
            tooltip: {
              // 自定义tooltip的文案
              formatter: (params) => {
                return `${params.name} 注册用户数：${params.value}`
              }
            },
            series: [{
              name: '数据',
              type: 'line',
              symbol: 'circle', // 设置圆点样式
              symbolSize: 6, // 设置圆点大小
              itemStyle: {
                color: '#275FE8', // 设置数据圆点颜色
                opacity: 1 // 设置圆圈透明度为1，即实心圆圈
              },
              lineStyle: {
                width: 1, // 设置数据线宽度为0，即去掉横线
                color: '#275FE8' // 设置数据线颜色
              },
              data: this.registerChartY
            }]
          })
          registerChart.hideLoading()
          activeEcharts.setOption({
            xAxis: {
              axisLabel: {
                textStyle: {
                  color: 'rgba(1, 1, 1, 0.4)' // 设置 x 轴字体颜色
                }
              },
              axisLine: {
                lineStyle: {
                  color: 'rgba(1, 1, 1, 0.1)' // 设置 x 轴线颜色
                }
              },
              axisTick: {
                show: false // 设置是否显示 X 轴的刻度线
              },
              data: this.activeEchartsX
            },
            yAxis: {
              axisLabel: {
                textStyle: {
                  color: 'rgba(1, 1, 1, 0.4)' // 设置 y 轴字体颜色
                }
              },
              axisLine: {
                lineStyle: {
                  color: 'rgba(1, 1, 1, 0.1)' // 设置 x 轴线颜色
                }
              },
              axisTick: {
                show: false // 设置是否显示 X 轴的刻度线
              },
              splitLine: {
                // show: false // 设置是否显示 Y 轴的分隔线
                lineStyle: {
                  color: 'rgba(1, 1, 1, 0.1)'
                }
              }
            },
            tooltip: {
              // 自定义tooltip的文案
              formatter: (params) => {
                return `${params.name} 活跃用户数：${params.value}`
              }
            },
            series: [{
              name: '数据',
              type: 'line',
              symbol: 'circle', // 设置圆点样式
              symbolSize: 6, // 设置圆点大小
              itemStyle: {
                color: '#275FE8', // 设置数据圆点颜色
                opacity: 1 // 设置圆圈透明度为1，即实心圆圈
              },
              lineStyle: {
                width: 1, // 设置数据线宽度为0，即去掉横线
                color: '#275FE8' // 设置数据线颜色
              },
              data: this.activeEchartsY
            }]
          })
        }
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 日期选择切换
    handleDate(type) {
      this.dateType = type
      if (type === 'day') {
        // this.$refs.mounthPicker?.hidePicker()
        // this.$nextTick(() => {
        //   this.$refs.datePicker.showPicker = true
        // })
      } else {
        this.startMounth = moment(moment().format("YYYY-MM-DD")).subtract(5, 'months').startOf('month').format('YYYY-MM-DD')
        this.endMounth = moment().format("YYYY-MM-DD")
        this.mounthValue = [this.startMounth, this.endMounth]
        // this.$nextTick(() => {
        //   this.$refs.dayPicker?.hidePicker()
        // })
      }
      this.init()
    },
    // 日期选择
    handleFormat(val) {
      if (this.dateType === 'day') {
        this.startDay = moment(val[0]).format("YYYY-MM-DD")
        this.endDay = moment(val[1]).format("YYYY-MM-DD")
      } else {
        this.startMounth = moment(val[0]).format("YYYY-MM-DD")
        this.endMounth = moment(val[1]).endOf('month').format("YYYY-MM-DD")
      }
      this.init()
    },
    // 导出
    handleExports(dataType) {
      const params = {
        productIds: this.productIds,
        type: this.dateType,
        startDate: this.dateType === 'day' ? this.startDay : this.startMounth,
        endDate: this.dateType === 'day' ? this.endDay : this.endMounth,
        dataType: dataType
      }
      statisticalExport(params).then(res => {
        this.exportBlobFile(res)
      }).catch(err => {
        this.$message.error(err.message)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.user {

  .title {
    font-size: 18px;
    font-weight: 400;
    color: #252525;
    margin-bottom: 21px;
  }

  .header {
    display: flex;

    .today-register,
    .accumulate-register,
    .today-active {
      background: rgba(39, 95, 232, 0.05);
      margin-right: 20px;
      padding: 15px;
      display: flex;
      justify-content: space-between;

      .left {
        margin-right: 20px;

        .head {
          font-size: 14px;
          font-weight: 400;
          color: #252525;
        }

        .num {
          font-size: 30px;
          font-weight: 500;
          color: #275FE8;
        }
      }

      .right {
        width: 77px;
        float: right;
        font-size: 14px;
        font-weight: 400;
        color: #252525;
        margin-top: 33px;
      }
    }
  }

  .search {
    display: flex;
    justify-content: space-between;
    margin-top: 37px;

    .name {
      padding: 10px;
      font-size: 18px;
      font-weight: 400;
      color: #252525;
      background: rgba(39, 95, 232, 0.1);
    }

    .search-right {
      display: flex;
      align-items: center;

      .tab {
        margin-right: 16px;
        display: flex;
        align-items: center;

        .day,
        .mounth {
          width: 88px;
          height: 32px;
          line-height: 32px;
          background: rgba(0, 0, 0, 0.05);
          border-radius: 4px;
          font-weight: 400;
          color: rgba(0, 0, 0, 0.4);
          font-size: 14px;
          text-align: center;
          cursor: pointer;
        }
        .day {
          margin-right: 16px;
        }

        .active {
          background: rgba(39,95,232,0.1);
          border: 1px solid rgba(39,95,232,0.4);
          color: #275FE8;
        }
      }
    }

    ::v-deep .el-date-editor--daterange.el-input__inner {
      width: 243px;
    }

    ::v-deep .el-date-editor--monthrange.el-input, .el-date-editor--monthrange.el-input__inner {
      width: 243px;
    }

    ::v-deep .el-range-separator {
      color: #636B76;
      padding: 0 20px 0 5px;
    }
  }

  .register-box,
  .active-box {
    margin-top: 32px;

    .header {
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
